package com.example.demo.service.impl;

import com.example.demo.constant.MessageConstant;
import com.example.demo.constant.PasswordConstant;
import com.example.demo.entity.User;
import com.example.demo.entity.UserDTO;
import com.example.demo.exception.PasswordErrorException;
import com.example.demo.exception.AccountNotFoundException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param userDTO
     * @return
     */
    public User login(UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //MD5加密 -> 在前端实现了md5加密，传过来的password就是密文
        //password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //3、返回实体对象
        return user;
    }


    /**
     * 新增用户
     * @param userDTO
     */
    public void save(UserDTO userDTO){
        User user = new User();

        // 拷贝属性 UserDTO -> User
        BeanUtils.copyProperties(userDTO, user);

        // 设置初始密码
        user.setPassword(
                DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        userMapper.insert(user);
    }

}
